<!--
 * @author wangjinqiu
 -->
<template>
  <div class="app-container hundredLearningEdit">
    <div class="main-title">新建/编辑</div>
    <section v-loading="loading" class="clock-main">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="200px"
        class="dataForm"
      >
        <el-form-item label="活动类型" prop="clockResourceType">
          <el-radio-group v-model="form.clockResourceType">
            <el-radio
              v-for="v in dict.DKZYLX"
              :key="v.dictValue"
              :label="v.dictValue"
            >{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="引导图" prop="coverImgId" required>
          <image-upload
            :key="uploadFile.imagecropperKey"
            v-model="form.coverImgId"
            :preview-id="uploadFile.viewId"
            :forever="true"
            :width="228"
            :view="uploadFile.view"
            :height="148"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="uploadFile.isOss"
            @changeOssPath="(path) =>{uploadFile.viewId = path}"
          />
        </el-form-item>
        <el-form-item label="背景颜色" prop="backColor">
          <el-color-picker v-model="form.backColor" />
        </el-form-item>
        <el-form-item label="标题颜色" prop="titleColor">
          <el-color-picker v-model="form.titleColor" />
        </el-form-item>
        <el-form-item label="温馨提示" prop="briefIntroduction">
          <tinymce v-if="showTinymce" v-model="form.briefIntroduction" :is-oss="uploadFile.isOss" :height="300" />
          <!--          <el-input
            v-model="form.briefIntroduction"
            :rows="6"
            type="textarea"
            placeholder="请输入简介"
          />-->
        </el-form-item>
        <el-form-item label="活动开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            style="width: 100%"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="活动结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            style="width: 100%"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
          />
        </el-form-item>
         <el-form-item label="结束后是否允许查看" prop="endsIsAllowView">
          <el-radio-group v-model="form.endsIsAllowView">
            <el-radio
              v-for="v in viewOptions"
              :key="v.value"
              :label="v.id"
            >{{ v.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动规则" prop="remark">
          <tinymce v-if="showTinymce" v-model="form.remark" :is-oss="uploadFile.isOss" :height="300" />
        </el-form-item>
        <el-form-item
          label="排行榜展示数量"
          prop="rankSizeLimit"
        >
          <el-input
            v-model.number="form.rankSizeLimit"
            style="width: 80%;"
            type="number"
            :disabled="numLimit"
            label="请输入排行榜展示数量"
          />
          <el-checkbox v-model="numLimit" style="margin-left: 30px;">不限制</el-checkbox>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>
    <section class="page-footer">
      <el-button @click="()=>{$router.back()}">取消</el-button>
      <el-button type="primary" @click="insertOrUpdate">确定</el-button>
    </section>
  </div>
</template>
<script>
import ImageUpload from '@/components/ImageUpload'
import { insert, update, get, getDictByCode } from '../api'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'PunchClockEdit',
  components: { Tinymce, ImageUpload },
  data() {
    return {
      loading: false,
      id: '', // 活动ID
      time: [],
      state: '',
      viewOptions:[
        {
          value:1,
          id:1,
          name:'允许'
        },
        {
          value:0,
          id:0,
          name:'不允许'
        },
      ],
      form: {
        clockResourceType: '',
        endsIsAllowView:0,
        name: '',
        coverImgId: '',
        backColor: '#f8f8f8',
        titleColor: '#000000',
        briefIntroduction: '',
        startTime: '',
        endTime: '',
        remark: '',
        rankSizeLimit: '',
        sort: ''
      },
      numLimit: false,
      dict: {
        DKZYLX: []
      },
      rules: {
        clockResourceType: [
          { required: true, message: '请选择活动类型', trigger: 'change' }
        ],
         endsIsAllowView: [
          { required: true, message: '请选择结束后是否允许查看', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        coverImgId: [
          { required: true, message: '请上传引导图', trigger: 'blur' }
        ],
        backColor: [
          { required: true, message: '请选择背景颜色', trigger: 'change' }
        ],
        titleColor: [
          { required: true, message: '请选择标题颜色', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请填写活动规则', trigger: 'blur' }
        ],
        briefIntroduction: [
          { required: true, message: '请填写温馨提示', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择活动开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请选择活动结束时间', trigger: 'blur' }
        ]
      },
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: '',
        fileIndex: 0,
        isOss: !!sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG')
      },
      showTinymce: false
    }
  },
  watch: {},
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    this.getDict('DKZYLX')
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.handleCancel()
          }
        })
      }
      this.id = this.$route.query.i || ''
      this.getData()
    } else {
      this.showTinymce = true
    }
  },
  methods: {
    cancel() {
      this.$router.back()
    },
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((response) => {
            this.dict[code] = response.data.data[0].list
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    insertOrUpdate() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (new Date(this.form.startTime).getTime() > new Date(this.form.endTime).getTime()) {
            this.$message({
              showClose: true,
              message: '活动开始时间不得晚于活动结束时间！',
              type: 'warning'
            })
            return false
          }
          const params = Object.assign({}, this.form)
          if (this.numLimit) {
            params['rankSizeLimit'] = -1
          }
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          if (this.state === 'create') {
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.cancel()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            params['id'] = this.id
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.cancel()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          }
        }
      })
    },
    // 获取详情
    getData() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: this.id }).then((res) => {
          loading.close()
          for (const i in this.form) {
            this.form[i] = res.data.data[i]
          }
          if (this.form['rankSizeLimit'] == -1) {
            this.form['rankSizeLimit'] = ''
            this.numLimit = true
          }
          if (res.data.data['coverImgIdURL']) {
            this.uploadFile.viewId = res.data.data['coverImgIdURL']
          }
          this.showTinymce = true
        }).catch((error) => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.hundredLearningEdit{
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  position: relative;
  .main-title{
    position: relative;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    padding: 0 20px;
    border-bottom: 1px solid #dfe2e2;
    /*margin-left: 20px;*/
    &::before{
      content: '';
      position: absolute;
      width: 3px;
      @include bg-color($mainColor);
      top: 15px;
      bottom: 15px;
      left: 15px;
    }
  }
  .clock-main{
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    padding: 20px 0;
    bottom: 52px;
    overflow: auto;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    .dataForm{
      width: 1000px !important;
      margin: 0 auto;
    }
  }
  .page-footer{
    position: absolute;
    width: 100%;
    bottom: 0;
    z-index: 99;
    background-color: #fff;
    text-align: center;
    padding:10px;
    box-shadow: 0 -3px 6px #f5f5f5;
    display: flex;
    justify-content: center;
  }
  .el-input__inner{
    text-align: left;
  }
}
</style>
